package com.fary.chapter01_aqs;

/**
 * @author Fary
 * @version 1.0
 * @description: TestInterrupt
 * @date 2021/8/19 9:39
 */
public class TestInterrupt {
    public static void main(String[] args) {
        Thread t = new Thread(new Worker());
        t.start();
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        t.interrupt();
        System.out.println("Main thread stopped.");
    }

    public static class Worker implements Runnable {
        public void run() {
            int i = 0;
            Thread c = Thread.currentThread();
            System.out.println("while之前线程中断状态isInterrupted()：" + c.isInterrupted());
            while (!Thread.interrupted()) {// 判断是否中断，如果中断，那么跳出并清除中断标志位
                System.out.println(c.getName() + "  " + i++ + "  " + c.isInterrupted());
            }
            System.out.println("while之后线程中断状态isInterrupted():" + c.isInterrupted()); // 为false，因为interrupt()会清除中断标志位，显示为未中断
            System.out.println("第二次及以后的interrupted()返回值：" + Thread.interrupted());
            c.interrupt();
            System.out.println("再次中断后查询中断状态isInterrupted():" + c.isInterrupted());
        }
    }
}
